package com.ghsc.ghxc.jsb.ui.message.activity

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSS
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.config.AppConfig
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.cn.appcore.utils.TimeUtils
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityChatTeamSetBinding
import com.ghsc.ghxc.jsb.ui.message.adapter.HeadListAdapter
import com.ghsc.ghxc.jsb.ui.message.bean.GroupDataResultBeans
import com.ghsc.ghxc.jsb.utils.OssUpUtils
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.ghsc.ghxc.jsb.view.SeeTextPopViiew
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.yunxin.kit.chatkit.repo.ConversationRepo
import com.netease.yunxin.kit.chatkit.repo.TeamRepo
import com.netease.yunxin.kit.corekit.event.EventCenter
import com.netease.yunxin.kit.corekit.im.custom.TeamEvent
import com.netease.yunxin.kit.corekit.im.custom.TeamEventAction
import com.netease.yunxin.kit.corekit.im.provider.FetchCallback

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：ChatTeamSetActivity
 * 创建时间：2024/5/9 10:44
 * 创建人 @author： xiaolin
 * 描述 ：Todo...群 右上角设置
 */
class ChatTeamSetActivity : BaseVMActivity<ChatViewModel, ActivityChatTeamSetBinding>()  {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_chat_team_set
    }

    override fun attachVMClass(): Class<ChatViewModel>? {
        return ChatViewModel::class.java
    }


    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    var userMyId : String by Preference(HttpConstant.USER_ID, "")
    var bundle : Bundle?=null
    var type:Int=0
    var targetId:String?=""
    var tId:String?=""



    var classify_id =0 //群分类


    //屏幕的宽度
    var widthPixels= AppConfig.getApplication().resources.displayMetrics.widthPixels
    //屏幕的密度
    var density= AppConfig.getApplication().resources.displayMetrics.density
    private val mAdapterHeadList : HeadListAdapter by lazy { HeadListAdapter((widthPixels/density)) }
    var rvHeadList = arrayListOf<GroupDataResultBeans>()

    var isTopStatus :Boolean = false // 是否置顶
    //    var isBlackstatis:Boolean=false//是否黑名单
    var signRoles:Int=0 // 9群主 8是管理员
    var isTaboo:Boolean =false //是否禁言
    var isSiXin:Boolean =false //是否私信

    val CHOOSE_PHOTO_1 = 1001
    private var selectHead: List<LocalMedia> = ArrayList()
    var pathHead = "" //头像地址
    private var themeId = 0
    //上传到阿里云服务器到图片url
    var aliUrlHead=""

    var islazyLoad=false //是否执行过

    override fun initView() {
        bundle=intent.extras
        type=bundle!!.getInt("type",0)
        targetId=bundle!!.getString("targetId","")
        tId=bundle!!.getString("tId","")
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableRefresh(false)
        binding.refreshLayout.setEnableOverScrollDrag(true)
        binding.bar.topTitle.text=if (type==1)  "聊天设置" else "群聊设置"
        binding.bar.topLeftView.setOnClickListener { finish() }

        binding.rvListhead.layoutManager = GridLayoutManager(this, 5)
        binding.rvListhead.adapter=mAdapterHeadList
        mAdapterHeadList.setNewInstance(rvHeadList)
        mAdapterHeadList.setOnItemClickListener { adapter, view, position ->
            if (type==3||type==10){
                if (mAdapterHeadList.getItem(position).uid== CustKey.CHAT_GROUP_LIST_ADD){
                    //添加
                    var  bundle =Bundle()
                    bundle.putString("gid",targetId)
                    startActivity(ChatListAddActivity().javaClass,bundle)
                }else if (mAdapterHeadList.getItem(position).uid==CustKey.CHAT_GROUP_LIST_DELETE){
                    //删除
                    // 查看群聊人员
                    var  bundle =Bundle()
                    bundle.putString("targetId",targetId)
                    bundle.putInt("sign",1)
                    startActivity(ChatTeamListActivity().javaClass,bundle)
                }else{
                    var  bundle =Bundle()
                    bundle.putString("gid",targetId)
                    bundle.putString("userIdTa",mAdapterHeadList.getItem(position).uid)
                    bundle.putInt("signRoles",signRoles)
                    startActivity(ChatSetSingleActivity().javaClass,bundle)
                }
            }else if (type==1){
                var  bundle =Bundle()
                bundle.putString("userIdTa",mAdapterHeadList.getItem(position).uid)
                startActivity(ChatSetSingleActivity().javaClass,bundle)
            }

        }
    }

    override fun onResume() {
        super.onResume()
        if(type==3 || type==10){
            onUpdata()
        }
    }
    /** 群的信息 **/
    private fun onUpdata(){
        binding.llBtnSee.visibility= View.VISIBLE
        binding.llType3.visibility= View.VISIBLE
        /** 根据群id 查询个人信息 是否是管理员或者群主 **/
        val map: HashMap<String, Any> = HashMap()
        map["gid"] = targetId!!
        map["userid"] = userMyId
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupUserInfoMethod(it1) }
    }

    override fun initData() {
        super.initData()
        binding.llBtnSee.setSingleClickListener {
            // 查看群聊人员
            var  bundle =Bundle()
            bundle.putString("targetId",targetId)
            bundle.putInt("sign",0)
            startActivity(ChatTeamListActivity().javaClass,bundle)
        }
        binding.tvBtnNext.setSingleClickListener {
            //拉黑 或者 退出群聊
            if(type==3){
                //群
                XPopup.Builder(this@ChatTeamSetActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .asCustom(
                        ConfirmCancelPopViiew(
                            this@ChatTeamSetActivity, "提示",  if (signRoles==9) "确定要将该群解散吗?" else "确定要退出该群聊吗?",
                            btnConfirm = {
                                showLoading()
                                if (signRoles==9){
                                    //解散
                                    val map: HashMap<String, Any> = HashMap()
                                    map["gid"] = targetId!!
                                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onDeleteGroupMethod(it1) }
                                }else {
                                    //退出
                                    val map: HashMap<String, Any> = HashMap()
                                    map["gid"] = targetId!!
                                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onExitGroupMethod(it1) }
                                }
                            },
                            btnCancel = {
                            },
                        )
                    )
                    .show()
            }
        }
        //群点击事件
        binding.run {
            llBtnUpGroupContent.setSingleClickListener {
                //修改群公告
                if (signRoles ==0){
                    if (!TextUtils.isEmpty(binding.tvNoticeContent.text.toString().trim())){
                        XPopup.Builder(this@ChatTeamSetActivity)
                            .asCustom(SeeTextPopViiew(this@ChatTeamSetActivity, "群公告", binding.tvNoticeContent.text.toString().trim())) .show()
                    }else {
                        showToast("暂无群公告")
                    }

                }else{
                    var  bundle =Bundle()
                    bundle.putString("targetId",targetId!!)
                    bundle.putInt("classify_id",classify_id)
                    bundle.putInt("sign",2)
                    bundle.putString("content",binding.tvNoticeContent.text.toString().trim())
                    startActivity(ChatGroupNameActivity().javaClass,bundle)
                }

            }
            llBtnUpGroupHead.setSingleClickListener {
                //修改群头像
                if (signRoles ==0){
                    showToast("只有群主或者群管理才可操作")
                    return@setSingleClickListener
                }
                PictureSelector.create(this@ChatTeamSetActivity)
                    .openGallery(PictureMimeType.ofImage())
                    .loadImageEngine(GlideEngine.createGlideEngine())
                    .theme(themeId)
                    .selectionMode(PictureConfig.SINGLE)
                    .imageSpanCount(4)
                    .previewImage(true)
                    .isCamera(true)
                    .enableCrop(true) // 是否裁剪
                    .compress(true) // 是否压缩
                    .freeStyleCropEnabled(true) // 裁剪框是否可拖拽
                    .scaleEnabled(true)
                    .withAspectRatio(16, 9)
//                .cropWH(345,128)// 裁剪宽高比，设置如果大于图片本身宽高则无效
//                .cropImageWideHigh()//
                    .minimumCompressSize(100) // 小于100kb的图片不压缩
                    .forResult(CHOOSE_PHOTO_1)
            }
            llBtnUpGroupName.setSingleClickListener {
                //修改群名称
                if (signRoles ==0){
                    showToast("只有群主或者群管理才可操作")
                    return@setSingleClickListener
                }
                var  bundle =Bundle()
                bundle.putInt("sign",1)
                bundle.putString("targetId",targetId!!)
                bundle.putInt("classify_id",classify_id)
                bundle.putString("content",binding.tvTitle.text.toString().trim())
                startActivity(ChatGroupNameActivity().javaClass,bundle)
            }
            llBtnType.setSingleClickListener {
                //修改群类型
            }

            ivSetTaboo.setSingleClickListener {
                //禁言
                showLoading()
                val map: HashMap<String, Any> = HashMap()
                map["gid"] = targetId!!
                map["ptype"]=if (isTaboo) 2 else 1
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupStopAllMethod(it1) }

            }
            ivSetSiXin.setSingleClickListener {
                //私信
                showLoading()
                val map: HashMap<String, Any> = HashMap()
                map["gid"] = targetId!!
                map["ptype"]=    if (isSiXin) 1 else 2
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupSiXinMethod(it1) }
            }
        }


    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ChatTeamSetActivity, Observer {
                dismissLoading()
                showToast(it)
            })
            againLoginMsg.observe(this@ChatTeamSetActivity, Observer {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            })
            onGroupStopAllData.observe(this@ChatTeamSetActivity){
                //设置禁言
                dismissLoading()
                showToast("设置成功")
                /** 群的信息 **/
                onUpdata()
            }
            onGroupSiXinData.observe(this@ChatTeamSetActivity){
                //设置私聊
                dismissLoading()
                showToast("设置成功")
                /** 群的信息 **/
                onUpdata()
            }
//            onDeleteFriendData.observe(this@ChatTeamSetActivity){
//                //删除好友
//                RxBus.getDefault().post(
//                    RxBusBean(CustSignKey.IM_DELETE_INFO, CustSignKey.IM_DELETE_INFO,targetId!!)
//                )
//                finish()
//            }
            onGroupUserInfoData.observe(this@ChatTeamSetActivity){
                //查询自己是否是管理元
                signRoles=it.data.data.roles
                if ( it.data.data.roles==9 || it.data.data.roles==8) {
                    binding.tvBtnNext.text="解散群聊"
                    binding.tvXianAdmin.visibility=View.VISIBLE
                    binding.llTaboo.visibility=View.VISIBLE
                    binding.llSiXin.visibility=View.VISIBLE
                }
                else{
                    binding.tvXianAdmin.visibility=View.GONE
                    binding.llTaboo.visibility=View.GONE
                    binding.llSiXin.visibility=View.GONE
                    binding.tvBtnNext.text="退出群聊"
                }
                /** 根据群id 查询群信息 **/
                val map: HashMap<String, Any> = HashMap()
                map["gid"] = targetId!!
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupInfoMethod(it1) }


            }
            onGroupInfoData.observe(this@ChatTeamSetActivity){
                //如果请求过的话。下次不更新其他。只刷新本地数据库容云群的信息
                if (!islazyLoad){
                    rvHeadList.clear()
                    rvHeadList = it.data.list as ArrayList<GroupDataResultBeans>
                    if (signRoles==9 || signRoles==8){
                        rvHeadList.add(GroupDataResultBeans(uid = CustKey.CHAT_GROUP_LIST_ADD))
                        rvHeadList.add(GroupDataResultBeans(uid = CustKey.CHAT_GROUP_LIST_DELETE))
                    }
                    mAdapterHeadList.replaceData(rvHeadList)
                    binding.tvId.text=it.data.data.gid
                    binding.tvTitle.text=it.data.data.name
                    binding.tvType.text=it.data.data.classify
                    binding.tvNoticeContent.text=it.data.data.gonggao
                    binding.tvConut.text="查看更多成员("+it.data.data.usercnt.toString()+")  >"
                    GlideUtil.ImageHeadLoad(this@ChatTeamSetActivity,it.data.data.headimg,binding.imgHead)
                    if (it.data.data.cansay==1){
                        //1是false正常  否则 就是禁言状态
                        isTaboo=false
                        binding.ivSetTaboo.isSelected=isTaboo
                    }else {
                        isTaboo=true
                        binding.ivSetTaboo.isSelected=isTaboo
                    }
                    if (it.data.data.cansixin==1){
                        //1是false正常  否则 就是禁言状态
                        isSiXin=true
                        binding.ivSetSiXin.isSelected=isSiXin
                    }else {
                        isSiXin=false
                        binding.ivSetSiXin.isSelected=isSiXin
                    }

                }else {
                    rvHeadList.clear()
                    rvHeadList = it.data.list as ArrayList<GroupDataResultBeans>
                    if (signRoles==9 || signRoles==8){
                        rvHeadList.add(GroupDataResultBeans(uid = CustKey.CHAT_GROUP_LIST_ADD))
                        rvHeadList.add(GroupDataResultBeans(uid = CustKey.CHAT_GROUP_LIST_DELETE))
                    }
                    mAdapterHeadList.replaceData(rvHeadList)
                    if (it.data.data.cansay==1){
                        //1是false正常  否则 就是禁言状态
                        isTaboo=false
                        binding.ivSetTaboo.isSelected=isTaboo
                    }else {
                        isTaboo=true
                        binding.ivSetTaboo.isSelected=isTaboo
                    }
                }
            }
            onDeleteGroupData.observe(this@ChatTeamSetActivity){
                //解散
                dismissLoading()
                if (!TextUtils.isEmpty(tId)){
                    dismissTeam(tId!!)
                }
                finish()
//                解散或者退出。都需要关闭会话。删除该会话
            }
            onExitGroupData.observe(this@ChatTeamSetActivity){
                //退出
                dismissLoading()
                if (!TextUtils.isEmpty(tId)){
                    EventCenter.notifyEvent(TeamEvent(tId!!, TeamEventAction.ACTION_DISMISS))
                    clearNotify(tId!!)
                    removeStickTop(tId!!)
                }
                finish()
            }
            onAliYunOosData.observe(this@ChatTeamSetActivity) {
                //阿里云
                var oss=  OssUpUtils.ossConfig(this@ChatTeamSetActivity,
                    it.data.ossHost,it.data.AccessKeyId,it.data.AccessKeySecret,it.data.SecurityToken)
                loge("头像="+pathHead)
                aliUrlHead=it.data.rootPATH+ CustKey.IMG_URL_HEAD_GROUP+ StringUtil.getTime()+"/"+targetId+ TimeUtils.getTime10()+(0..100).random()+".png"
                loge("头像=--===="+aliUrlHead)
                upload(oss,it.data.bucketName, pathHead,aliUrlHead)
            }
            onUpGroupInfoData.observe(this@ChatTeamSetActivity){
                //修改头像
                showToast("修改成功")
                /** 群的信息 **/
                onUpdata()
            }
        }
    }
    /**
     * bucketName 仓库名
     * uploadFilePath  阿里服务器的路径
     * objectName  图片地址
     */
    fun upload(oss: OSS, bucketName:String, objectName:String, uploadFilePath:String){
        /**
         * bucketName
         * uploadFilePath 后台给的路径。是放在阿里服务器的某个路径下
         * objectName 本地上传的路径。比如上传的xxx/xxx/xxx.png
         */
        val put = PutObjectRequest(bucketName, uploadFilePath,objectName)
        // 异步上传时可以设置进度回调。
        put.progressCallback =
            OSSProgressCallback { request, currentSize, totalSize ->
            }
        val task: OSSAsyncTask<*> = oss.asyncPutObject(
            put,
            object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult) {
                    loge("onSuccess-ETag"+result.eTag)
                    dismissLoading()
                    //修改群头像
                    val map: HashMap<String, Any> = HashMap()
                    map["headimg"] = aliUrlHead
                    map["gid"] =targetId!!
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onUpGroupInfoMethod(it1) }

                }
                override fun onFailure(
                    request: PutObjectRequest?,
                    clientExcepion: ClientException,
                    serviceException: ServiceException
                ) {
                    // 请求异常。
                    if (clientExcepion != null) {
                        // 客户端异常，例如网络异常等。
                        clientExcepion.printStackTrace()
                    }
                    if (serviceException != null) {
                        // 服务端异常。
                        Log.e("onFailure-ErrorCode", serviceException.errorCode)
                        Log.e("onFailure-RequestId", serviceException.requestId)
                        Log.e("onFailure-HostId", serviceException.hostId)
                        Log.e("onFailure-RawMessage", serviceException.rawMessage)
                    }
                    dismissLoading()
                    showToast("上传失败，请重试...")
                }
            })
//        取消上传任务。
//        task.cancel();
//        等待上传任务完成。
//        task.waitUntilFinished();
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_OK -> when (requestCode) {
                CHOOSE_PHOTO_1 -> {
                    // 图片选择结果回调
                    selectHead = PictureSelector.obtainMultipleResult(data)
                    for (media in selectHead) {
                        Log.i("图片-----》", media.path)
                        pathHead = if (media.isCut && !media.isCompressed) {
                            // 裁剪过
                            media.cutPath
                        } else if (media.isCompressed || media.isCut && media.isCompressed) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            media.compressPath
                        } else {
                            // 原图
                            media.path
                        }
                        GlideUtil.ImageHeadLoad(this,pathHead,binding.imgHead)
                        //todo 上传头像
                        showLoading()
                        mViewModel.onAliYunOosMethod("")
                    }
                }
            }
            else -> {
            }
        }
    }
    //清除未读
    fun clearNotify(teamId: String) {
        ConversationRepo.setNotify(
            teamId,
            SessionTypeEnum.Team,
            true,
            object : FetchCallback<Void> {
                override fun onSuccess(param: Void?) {
                    loge("clearNotify==onSuccess")
                }

                override fun onFailed(code: Int) {
                }

                override fun onException(exception: Throwable?) {
                }
            })
    }
    //取消置顶
    fun removeStickTop(teamId: String) {
        if (ConversationRepo.isStickTop(teamId, SessionTypeEnum.Team)) {
            ConversationRepo.removeStickTop(
                teamId,
                SessionTypeEnum.Team,
                "",
                object : FetchCallback<Void> {
                    override fun onSuccess(param: Void?) {
                        loge("removeStickTop==onSuccess")
                    }

                    override fun onFailed(code: Int) {
                    }

                    override fun onException(exception: Throwable?) {
                    }
                })
        }
    }
    //解散群
    fun dismissTeam(teamId: String) {
        EventCenter.notifyEvent(TeamEvent(teamId, TeamEventAction.ACTION_DISMISS))
        TeamRepo.dismissTeam(
            teamId,
            object : FetchCallback<Void> {
                override fun onSuccess(param: Void?) {
                }

                override fun onFailed(code: Int) {
                }

                override fun onException(exception: Throwable?) {
                }
            })
    }

}